package web2021.team1.lj.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import web2021.team1.lj.domain.User;
import web2021.team1.lj.service.UserService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;



@Controller
@RequestMapping("/admin")
public class UserController {
    @Autowired
    private UserService userService;


    @RequestMapping(value = "/register.do", method = RequestMethod.POST)
    public ModelAndView registerPage(String username, String password, HttpSession session) throws Exception {
        boolean isFlag = userService.registerUser(username, password);
        if(isFlag) {
            System.out.println("注册成功");
            return new ModelAndView("registSuccess");
        }else {
            return new ModelAndView("register").addObject("msg","用户名已存在请重试");
        }
    }

    @RequestMapping(value = "/login.do" ,method = RequestMethod.POST)
    public ModelAndView loginCheck(String username, String password, HttpSession session) throws Exception {

//        username = (String) session.getAttribute(username);
//        password = (String) session.getAttribute(password);


        if(username == null) {
            return new ModelAndView("login").addObject("msg","用户名不能为空");
        }

        User user = userService.findUserByUserName(username);
        System.out.println(user);
        System.out.println(username);
        System.out.println(password);

        session.setAttribute("user",user);

        //判断用户名是否不在数据库中
        if (user.getUserName() == null) {
            System.out.println("没有此用户");
            return new ModelAndView("login").addObject("msg", "没有此用户");
        } else if(password == null) {
            //判断密码是否为空
            System.out.println("密码不能为空！");
            return new ModelAndView("login").addObject("msg", "密码不能为空！");
        }else if (!user.getPassword().equals(password)) {
            //判断登录的用户密码与数据中是否匹配
            System.out.println("密码错误，请重试！");
            return new ModelAndView("login").addObject("msg", "密码错误");
        } else {
            //匹配，可以登录
            System.out.println("验证通过");
            userService.loginSuccess(user);

            return new ModelAndView("main").addObject("msg", "登录成功");

        }
    }
}
